package com.frame.util;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Hex;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * @Title: 系统
 * @Description:
 * @Copyright: Copyright (c) 2015
 * @Company:
 * @author 王海锋
 * @CreatedTime:2015-9-10 上午10:55:48
 * @version 1.0
 */

public class EncryptUtil {
	private static final String DEFAULTKEY="WHFdataKey@258!";
	private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5',
			'6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
	//加密密钥
	private static Cipher cipher;                      //加密算法
	private static KeyGenerator kgen;

	static{
		try {
			kgen = KeyGenerator.getInstance("AES");
			cipher = Cipher.getInstance("AES");
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] d){
		try {
			String v="154656";
			String a= EncryptUtil.encode(v);
//        	String s=EncryptUtil.desEncode(a);
//			System.out.println(EncryptUtil.desEncode(v));
//			System.out.println(EncryptUtil.decrypt(a));
//			String b=EncryptUtil.desDecrypt(s);
//			System.out.println(b);
//			System.out.println(EncryptUtil.decrypt(b));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/**
	 *
	 * 功能:标准MD5加密<br>
	 * 参数:<br>
	 * 作者:王海锋<br>
	 * 时间:2015-9-10 上午11:00:10<br>
	 * 说明:<br>
	 * 变更:<br>
	 */
	public static String md5Encode(String str){
		try {
			MessageDigest messageDigest = MessageDigest.getInstance("MD5");
			messageDigest.update(str.getBytes());
			byte[] bytes=messageDigest.digest();
			int len = bytes.length;
			StringBuilder buf = new StringBuilder(len * 2);
			// 把密文转换成十六进制的字符串形式
			for (int j = 0; j < len; j++) {
				buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
				buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
			}
			return buf.toString();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	public static String encode(String content) {
		return aesEncode(content,DEFAULTKEY);
	}

	public static String encode(String content, String key) {
		return aesEncode(content,key);
	}
	public static String aesEncode(String content) {
		return aesEncode(content,DEFAULTKEY);
	}


	public static String aesEncode(String content, String key) {
		if(content==null || content.length()<1)return null;
		try {
			kgen.init(128, new SecureRandom(key.getBytes()));
			SecretKey secretKey = kgen.generateKey();
			byte[] enCodeFormat = secretKey.getEncoded();
			SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES");
			byte[] byteContent = content.getBytes("utf-8");
			cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
			byte[] byteRresult = cipher.doFinal(byteContent);
			return new String(Hex.encodeHex(byteRresult));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String decrypt(String value) {
		return decrypt(value,DEFAULTKEY);
	}
	/**
	 * 解密
	 *
	 * @param content
	 *            待解密内容
	 * @param key
	 *            解密的密钥
	 * @return
	 */
	public static String decrypt(String value, String key) {
		if (value==null || value.length() < 1)
			return null;
		try {
			byte[] byteRresult = Hex.decodeHex(value.toCharArray());
			kgen.init(128, new SecureRandom(key.getBytes()));
			SecretKey secretKey = kgen.generateKey();
			byte[] enCodeFormat = secretKey.getEncoded();
			SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES");
			cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
			byte[] result = cipher.doFinal(byteRresult);
			return new String(result);
		}catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	/**
	 *
	 * 功能:SHA加密<br>
	 * 参数:<br>
	 * 作者:王海锋<br>
	 * 时间:2016-9-29下午10:09:04<br>
	 */
	public static String shaEncode(String text) {
		MessageDigest md = null;
		String outStr = null;
		try {
			md = MessageDigest.getInstance("SHA-1");
			byte[] digest = md.digest(text.getBytes());
			outStr = byteToString(digest);
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException(e);
		}
		return outStr;
	}
	public static String shaEncode(String text,String type) {
		return shaEncode(text,"SHA1");
	}

	/**
	 *
	 * 功能:AES加密<br>
	 * 参数:<br>
	 * 作者:王海锋<br>
	 * 时间:2016-5-12上午12:08:09<br>
	 * @throws Exception
	 */
	public static String desEncode(String text) throws Exception {
		return desEncode(text,DEFAULTKEY);
	}
	public static String desEncode(String text,String key) throws Exception {
		SecureRandom sr = new SecureRandom();

		// 从原始密钥数据创建DESKeySpec对象
		DESKeySpec dks = new DESKeySpec(key.getBytes());

		// 创建一个密钥工厂，然后用它把DESKeySpec转换成SecretKey对象
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		SecretKey securekey = keyFactory.generateSecret(dks);

		// Cipher对象实际完成加密操作
		Cipher cipher = Cipher.getInstance("DES");

		// 用密钥初始化Cipher对象
		cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);

		byte[] bt =cipher.doFinal(text.getBytes());
		String strs = new BASE64Encoder().encode(bt);
		return strs;
	}
	public static String desDecrypt(String value) throws Exception {
		return desDecrypt(value,DEFAULTKEY);
	}
	public static String desDecrypt(String value,String key) throws Exception {
		if (value == null)
			return "";
		BASE64Decoder decoder = new BASE64Decoder();
		byte[] buf = decoder.decodeBuffer(value);
		// 生成一个可信任的随机数源
		SecureRandom sr = new SecureRandom();

		// 从原始密钥数据创建DESKeySpec对象
		DESKeySpec dks = new DESKeySpec(key.getBytes());

		// 创建一个密钥工厂，然后用它把DESKeySpec转换成SecretKey对象
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		SecretKey securekey = keyFactory.generateSecret(dks);

		// Cipher对象实际完成解密操作
		Cipher cipher = Cipher.getInstance("DES");

		// 用密钥初始化Cipher对象
		cipher.init(Cipher.DECRYPT_MODE, securekey, sr);

		byte[] bt =cipher.doFinal(buf);
		return new String(bt);
	}


	private static String byteToString(byte[] digest) {
		StringBuilder buf = new StringBuilder();
		for (int i = 0; i < digest.length; i++) {
			String tempStr = Integer.toHexString(digest[i] & 0xff);
			if (tempStr.length() == 1) {
				buf.append("0").append(tempStr);
			} else {
				buf.append(tempStr);
			}
		}
		return buf.toString().toLowerCase();
	}
	private static String byte2hex(byte[] b) {
		String hs = "";
		String stmp = "";
		for (int n = 0; n < b.length; n++) {
			stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
			if (stmp.length() == 1)
				hs = hs + "0" + stmp;
			else
				hs = hs + stmp;
		}
		return hs.toUpperCase();
	}
}
